function adjust_content_frame(){
	var sidebar = document.getElementById("sidebar");
	var content_main = document.getElementById("content-main");
	if (sidebar.scrollHeight < content_main.scrollHeight) {
		sidebar.style.height = content_main.scrollHeight+"px";
		if( parseInt(content_main.style.height) < content_main.scrollHeight && content_main.style.height )
		{
			content_main.style.height = content_main.scrollHeight+"px";
		}
	} else if (sidebar.scrollHeight > content_main.scrollHeight) {
		content_main.style.height = sidebar.scrollHeight+"px";
	}
}

var MessageBox = Class.create();

Object.extend(MessageBox, {
	TYPE_YES_NO: 'type_yes_no',
	TYPE_OK_CANCEL: 'type_ok_cancel',
	TYPE_MESSAGE: 'type_message',
	TYPE_PROMPT: 'type_prompt',
	TYPE_CUSTOM: 'type_custom',
	TYPE_HTML:   'type_html',
	TYPE_ADDFRIEND: 'type_addfriend',
	TYPE_CREATE_SNAP: 'type_create_snap',
	showError: function(msg){
		new MessageBox(MessageBox.TYPE_MESSAGE, (msg['descriptions']!='')?msg['descriptions']:__lang[msg['reason']], '错误', {});
	},
	TEMPLATE_FRAME: '<div class="popup" id="panel" style="position: absolute; width:#{width}px; z-index:1000">\
	<div class="panel_wrap">\
	<div class="popup-top">\
		<div class="popup-top-right">\
			<div class="popup-top-mid"></div>\
		</div>	\
	</div>\
	<div class="popup-mid">\
		<div class="popup-mid-main">\
			  <div class="popup-mid-main-top">\
			      <a title="关闭窗口" target="_self" class="popup-closebtn close" href="javascript:;"></a>\
				  <div class="popup-mid-main-top-title">\
				    #{title}\
				  </div>\
			  </div>\
			  <div class="popup-mid-main-mid">\
				  <div class="popup-mid-main-mid-content">\
				  #{message}\
				  </div>\
			  </div>\
			  <div class="popup-mid-main-bottom">\
			     #{BUTTONS}\
			  </div>\
		</div>	  \
	</div>\
	<div class="popup-bottom">\
		<div class="popup-bottom-right">\
			<div class="popup-bottom-mid"></div>\
		</div>\
	</div>\
	</div>\
</div>',
	TEMPLATE_CREATE_SNAP: '<div class="popup" id="panel" style="position: absolute; width:#{width}px; z-index:1000">\
	<div class="mt13" style="width:380px;">\
  <div class="popup">\
	<div class="popup-top">\
		<div class="popup-top-right">\
			<div class="popup-top-mid"></div>\
		</div>\
	</div>\
	<div class="popup-mid">\
		<div class="popup-mid-main">\
			  <div class="popup-mid-main-top">\
			      <a href="javascript:;" class="popup-closebtn close" target="_self" title="关闭窗口"></a>\
				  <div class="popup-mid-main-top-title">\
				      创建快照\
				  </div>\
			  </div>\
			  <div class="popup-mid-main-mid">\
				  <div class="popup-mid-main-mid-content text-centerfix">\
<div class="edit-item">\
  <form id="form1" name="form1" method="post" action="">\
<div class="text-leftfix">标题：<input id="#{id}title" name="标题：" type="text" size="37" value="#{title}" /></div>\
<div class="mt13 text-leftfix">描述：<textarea id="#{id}content" name="" cols="30" rows="3" >#{content}</textarea> </div>\
  <span style="color: red;" id="snap_reason"></span></form>\
<div class="clearfix"></div></div>\
				  </div>\
			  </div>\
			  <div class="popup-mid-main-bottom">\
			      #{BUTTONS}\
			  </div>\
		</div>\
	</div>\
	<div class="popup-bottom">\
		<div class="popup-bottom-right">\
			<div class="popup-bottom-mid"></div>\
	</div></div></div></div></div>',
	TEMPLATE_ADDFRIEND:'<div class="popup" id="panel" style="position: absolute; width:#{width}px; z-index:1000">\
	<div class="popup-top">\
		<div class="popup-top-right">\
			<div class="popup-top-mid"></div>\
		</div>	\
	</div>\
	<div class="popup-mid">\
		<div class="popup-mid-main">\
			  <div class="popup-mid-main-top">\
			      <a title="关闭窗口" target="_self" class="popup-closebtn close" href="javascript:;"></a>\
				  <div class="popup-mid-main-top-title">\
				    请求加 #{username} 为好友\
				  </div>\
			  </div>\
			<form method="post" action="/~friends.index.add" id="add_friend_form">\
			  <div class="popup-mid-main-mid">\
				  <div class="popup-mid-main-mid-content">\
				  <ul class="add-my-friend">\
				     <li class="leftfix">\
					    <div class="avatar50">\
						    <a href="/?uid=#{uid}">\
							<img src="#{avatar}"/>\
							</a>\
					    </div>\
				     </li>\
					 <li class="rightfix">\
						 <p>需通过#{username}的验证才能加他为好友。\
					     <span>给#{the}的附加信息：</span><span style="color:red" id="no_reason"></span></p>\
					     <input type="hidden" name="add_uid" value="#{uid}">\
						 <textarea name="message" cols="" rows=""></textarea>\
					 </li>\
				 </ul>\
		<div class="clearfix"></div>\
				  </div>\
			  </div>\
			  <div class="popup-mid-main-bottom">\
			     #{BUTTONS}\
			  </div>\
			</form>\
		</div>\
	</div>\
	<div class="popup-bottom">\
		<div class="popup-bottom-right">\
			<div class="popup-bottom-mid"></div>\
		</div>\
	</div>\
</div>',	
	BUTTON_YES_NO: '<button class="cbtn1 yes">是</button><button class="cbtn no">否</button>',
	BUTTON_OK_CANCEL: '<button class="cbtn1 ok">确定</button><button class="cbtn cancel">取消</button>',
	BUTTON_MESSAGE: '<button class="cbtn1 close">关闭</button>',
	BUTTON_PROMPT: '<button class="cbtn1 ok">确定</button><button class="cbtn cancel">取消</button>',
	BUTTON_CUSTOM: '<button class="cbtn1 ok">确定</button><button class="cbtn cancel">取消</button>',
	BUTTON_ADDFRIEND: '<button class="cbtn1 ok" type="button">提交</button><button class="cbtn cancel" type="button">取消</button>',
	BUTTON_CREATE_SNAP: '<button class="cbtn1 ok">提交</button><button class="cbtn cancel">取消</button>',
	BUTTON_TRANSFER: '<button class="cbtn1 ok">使用其他道具</button><button class="cbtn cancel">退出</button>'
});

Object.extend(MessageBox.prototype, {
	type: '',
	callback: {},
	initialize: function(type, message, title, callback, more){
//		alert(1);
		if(!more) more = {};
		if(!more['width']) more['width'] = 400;
		this.type = type;
		this.callback = callback?callback:this.callback;
		var template = this.createTemplate(type); 
		
		if(!more['button'])
			var button_group_name = "BUTTON" + type.substring(type.indexOf('_')).toUpperCase();
		else 
			var button_group_name = "BUTTON"+"_"+more['button'].toUpperCase();
			
		var html = template.evaluate(Object.extend(more, {message: message, title: title, BUTTONS: MessageBox[button_group_name]}));
		new Insertion.Top($(document.body), html);
		this.show();
		this.bindHandlers(type);
	},
	createTemplate: function(type){
		var template_name = "TEMPLATE" + type.substring(type.indexOf('_')).toUpperCase();
		var template = MessageBox[template_name]?MessageBox[template_name]:MessageBox.TEMPLATE_FRAME;
		return new Template(
			template +
			"<div id='ieOpacityLayer' style='position: absolute; background: #000; z-index:998; FILTER: alpha(opacity=50); opacity: 0.5'></div>"
			);
	},
	bindHandlers: function(){
		switch(this.type){
			case MessageBox.TYPE_YES_NO:
				var btnYes = $$('#panel .yes')[0];
				var btnNo = $$('#panel .no')[0];
				btnYes.observe('click', this.onYesClick.bindAsEventListener(this));
				btnNo.observe('click', this.onNoClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_OK_CANCEL:
				var btnOk = $$('#panel .ok')[0];
				var btnCancel = $$('#panel .cancel')[0];
				btnOk.observe('click', this.onOkClick.bindAsEventListener(this));
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_PROMPT:
				var btnOk = $$('#panel .ok')[0];
				var btnCancel = $$('#panel .cancel')[0];
				btnOk.observe('click', this.onPromptOkClick.bindAsEventListener(this));
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_CUSTOM:
				var btnOk = $$('#panel .ok')[0];
				var btnCancel = $$('#panel .cancel')[0];
				btnOk.observe('click', this.onCustomOkClick.bindAsEventListener(this));
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_HTML:
				if ($$('#panel .ok')[0]) {
					var btnOk = $$('#panel .ok')[0];
					btnOk.observe('click', this.onHtmlOkClick.bindAsEventListener(this));
				}
				var btnCancel = $$('#panel .cancel')[0];
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_ADDFRIEND:
				var btnOk = $$('#panel .ok')[0];
				var btnCancel = $$('#panel .cancel')[0];
				btnOk.observe('click', this.onFriendOkClick.bindAsEventListener(this));
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_CREATE_SNAP:
				var btnOk = $$('#panel .ok')[0];
				var btnCancel = $$('#panel .cancel')[0];
				btnOk.observe('click', this.onFriendOkClick.bindAsEventListener(this));
				btnCancel.observe('click', this.onCancelClick.bindAsEventListener(this));
			break;
			case MessageBox.TYPE_MESSAGE:
			default:
				break;
		}
		var self = this;
		$$('#panel .close').each(function(v){
			v.observe('click', self.onCloseClick.bindAsEventListener(self));
		});
	},
	show: function(){
		this.hideSelect();
		try{
			this.handleFlash();
		}catch(e){
//			alert(e.message);
		}
		if($('ieOpacityLayer')){
			$('ieOpacityLayer').setStyle({left: '0', top: '0', height: $(document.documentElement).scrollHeight+"px", width: '100%'});
		}
		$('panel').show();

		var msg = $('panel');
		var clientHeight = document.documentElement.clientHeight ;
		var clientWidth = document.documentElement.clientWidth;
		var width = msg.getWidth();
		var height = msg.getHeight();
//		alert(document.documentElement.scrollTop);
		var top = (clientHeight - height)/2 + document.documentElement.scrollTop+document.body.scrollTop - (clientHeight - height)/2 * 0.3;
		var left = (clientWidth - width)/2;
		msg.setStyle({top: top + "px", left: left + "px"});
	},
	close: function(){
		this.showSelect();
		this.undoFlash();
		$('panel').hide();
		$('panel').remove();
		if($('ieOpacityLayer')){
			$('ieOpacityLayer').remove();
		}
		$$('select').each(function(item) { item.show();});
	},
	showError: function(error){
		$('mbox_error').show();
		$('mbox_msg').innerHTML = error;
	},
	onYesClick: function(event){
			if(this.callback['yes']){
				this.callback['yes']();
			}
			this.close();
	},
	onNoClick: function(event){
		if(this.callback['no']){
			this.callback['no']();
		}
		this.close();
	},
	onPromptOkClick: function(event){
		if(this.callback['ok']){
			this.callback['ok']($$('#panel .text')[0].value, this);
		}else{
			this.close();
		}
	},
	onCustomOkClick: function(event){
		if(this.callback['ok']){
			this.callback['ok']();
		}else{
			this.close();
		}
	},
	onHtmlOkClick: function(event){
		if(this.callback['ok']){
			this.callback['ok']();
		} else {
			this.close();
		}
	},
	onOkClick: function(event){
		try{
			if(this.callback['ok']){
				r = this.callback['ok']();
			}
			this.close();
		}catch(e){}
	},
	onFriendOkClick: function(event){
		var r = true;
		var btnOk = $$('#panel .ok')[0];
		btnOk.disabled = true;
		if(this.callback['ok']){
			r = this.callback['ok']();
		}
		btnOk.disabled =  false;
		if(r){
			this.close();
		}
	},
	onCancelClick: function(event){
		if(this.callback['cancel']){
			this.callback['cancel']();
		}
		this.close();
	},
	onCloseClick:function(event){
		if(this.callback['close']){
			this.callback['close']();
		}
		this.close();
	},
	hideSelect: function(){
		$$('select').each(function(item){
			if(!item.descendantOf($('panel'))) {
				item.setStyle({visibility: 'hidden'});
			}
		});
	},
	handleFlash: function(){
		if(isIE){
			var objs = $$('object');
			objs.each(function(item){
//				alert(item.outerHTML);
//				alert(item.childNodes.length);
//				var find = false;
//				var flag = false;
//				item.childElements().each(function(param){
//					
//					alert(param.name+"="+param.value);
//					if(param.tagName=="PARAM" && param.readAttribute('name').toUpperCase() == 'WMODE'){
//						
//						alert(1);
//						find = true;
//						if(param.readAttribute('value').toUpperCase() != 'TRANSPARENT'){
//							
//							alert(2);
//							flag = true;
//						}
//						throw $break;		
//					}
//				});
//				if(!find){
//					item.insert("<param name='wmode' value='transparent'/>");
//					var html = item.outerHTML;
//					item.insert({after:html});
//					item.remove();
//				}else{
//					if(flag){
//						var html=item.outerHTML;
//						html = html.gsub(/<PARAM NAME=\"WMode\" VALUE=\"Window\">/ig, "<PARAM NAME='WMODE' VALUE='TRANSPARENT'/>");
//						item.insert({after:html});
//						item.remove();
//					}
//				}
				var regex = /<param\s+name=[\"\']?wmode[\"\']?\s+value=[\"\']?([a-z]+)[\"\'][^>]*>/ig;
				var match = regex.exec(item.outerHTML);
				if(match==null || (match!=null && match[1].toUpperCase()!='TRANSPARENT')){
					var html = item.outerHTML.replace(regex, '');
					html = html.substring(0, html.indexOf("</OBJECT>")) + "<PARAM NAME='wmode' VALUE='transparent'/></OBJECT>";
					item.insert({after:html});
					item.remove();
				}				
			});
		}
		var objs = $$('embed');
		objs.each(function(item){
			
//			alert(item.outerHTML);
			var flag = (item.readAttribute('wmode') && (item.readAttribute('wmode').toUpperCase() == "TRANSPARENT"));
			if(!flag){
				var outerHTML = '';
				if(isIE){
//					item.writeAttribute('wmode', 'transparent');
					outerHTML = item.outerHTML;
					outerHTML = outerHTML.substring(0,outerHTML.indexOf(">")).replace(/wmode=[^\s]*/ig, '') + " wmode='transparent' cope='yes'/>";
//					alert(outerHTML);
				}else{
					var a= item.attributes, outerHTML="<"+item.tagName, i=0;for(;i<a.length;i++) 
				    if(a[i].specified) {
				      	if(a[i].name.toUpperCase() != "WMODE"){
				           	outerHTML +=" "+a[i].name+'="'+a[i].value+'"'; 
				       	}
				    }
				    outerHTML +=" wmode='transparent'"; 
				    outerHTML += " copy='yes'/>";
				}
				
				item.insert({after:outerHTML});
//				alert(outerHTML);
				if(isIE){
					item.outerHTML = '';
				}else{
					item.remove();
				}
			}
		});
		
	},
	undoFlash: function(){
		/*
		try{
			var objs = [];
			objs = $$('object[handle="yes"]');
			alert("object="+objs.length);
			if(objs){
				objs.each(function(item){
					item.show();
					item.writeAttribute('handle', 'no');
					var next = item.next();
					if(next) next.remove();
				});
			}
			objs = $$('embed[handle="yes"]');
			alert("embed="+objs.length);
			if(objs){
				objs.each(function(item){
					item.show();
					item.writeAttribute('handle', 'no');
					var next = item.next();
					if(next) next.remove();
				});
			}
		}catch(e){
			alert(e.message);
		}
		*/
	},
	showSelect:function(){
		$$('select').each(function(item){
			item.setStyle({visibility: 'visible'});
		});
	}
});
/**
<input type='button' value='yes_no' onclick="new MessageBox(MessageBox.TYPE_YES_NO,'123', 'damned',{yes:function(){alert('yes');}, no:function(){alert('no');}});"/>
<input type='button' value='ok_cancel' onclick="new MessageBox(MessageBox.TYPE_OK_CANCEL,'123', 'damned',{ok:function(){alert('yes');}, cancel:function(){alert('no');}});"/>
<input type='button' value='message' onclick="new MessageBox(MessageBox.TYPE_MESSAGE,'123', 'damned',{close:function(){alert('yes');}});"/>
**/

var Tabnav = Class.create();
Object.extend(
	Tabnav,
	{
		select: function(item, id){
			$$('#'+id+' li').each(function(item){
				item.removeClassName('selected');
			});
			item.addClassName('selected');
		}
	}
);

var ImageLoader = Class.create();
Object.extend(ImageLoader, {
	onError: function(event){
		var element = Event.element(event);
		this.loadDefault(element);
		element.onerror = function(){};
	},
	bindHandlers: function(){
		var self = this;
		$$('.avatar').each(function(item){
			item.onerror = self.onError.bindAsEventListener(self);
		});
//		if(isIE){
			new PeriodicalExecuter(this.IETimer.bind(this), 3); 
//		}
	},
	reload: function(){
		$$('.avatar').each(function(item){
			item.src= item.src+"?"+Math.random();
			item.onerror = self.onError.bindAsEventListener(self);
		});
	},
	IETimer: function (pe){
		var avatars = $$('.avatar');
		if(avatars.length==0) pe.stop();
		var completeCount = 0;
		var self = this;
		avatars.each(function(item){
			switch(item.readyState){
				case 'complete':
					completeCount++;
					break;
				case 'uninitialized':
					self.loadDefault(item);
					break;
			}
		});
//		if(completeCount == avatars.length) pe.stop();
	},
	loadDefault: function(img){
		var src = img.src;
		src = src.substring(src.lastIndexOf("/")+1, src.length);
		src = src.substring(0,src.indexOf("_"));
		img.src = "/images/"+src+"_default.jpg";
	}
});


var BirthdayChooser = Class.create();
Object.extend(BirthdayChooser, {
	YEAR_START: 1900,
	MONTH_DAY : [31,28,31,30,31,30,31,31,30,31,30,31],
	ASTRO: [
		['白羊座', '3-21', '4-20', 'aries'],
		['金牛座', '4-21', '5-21', 'taurus'],
		['双子座', '5-22', '6-21', 'gemini'],
		['巨蟹座', '6-22', '7-22', 'cancer'],
		['狮子座', '7-23', '8-23', 'leo'],
		['处女座', '8-24', '9-23', 'virgo'],
		['天秤座', '9-24', '10-23', 'libra'],
		['天蝎座', '10-24', '11-22', 'scorpio'],
		['射手座', '11-23', '12-21', 'sagittariu'],
		['魔羯座', '12-22', '1-20', 'capaicorn'],
		['水瓶座', '1-21', '2-19', 'aquarius'],
		['双鱼座', '2-20', '3-20', 'pisces'] 
	],
	isLeapYear: function(year){
		return year%400==0 || (year%4==0 && year%100!=0);
	},
	getAstro: function(month, day){
		if(month==0 || day==0) return '';
		var v = this.ASTRO.find(function(item){
			var min = parseInt(item[1].replace('-', '0'));
			var max = parseInt(item[2].replace('-', '0'));
			var value = parseInt(month+"0"+((day+"").length<2?("0"+day):day));
			if(value>=min && value<=max){
				return true;
			}else{
				return false;
			}
		});
		if(v){
			return v[0];
		}else{
			return '摩羯座';
		}
	},
	getAstroIcon: function(name){
		var template = new Template('<span class="icon_c #{name_en}" title="#{name}"></span>');
		var find = BirthdayChooser.ASTRO.find(function(v){
			return v[0] == name;
		});
		return template.evaluate({name: name, name_en: find[3]});
	}
});


Object.extend(BirthdayChooser.prototype, {
	d: [],
	initialize: function(birthday){
		this.d = birthday.split("-");
	},
	getHTML: function(){
		var ret = '';
		ret += '<select name="year" id="birthday_year"><option value="0">-年-</option></select> '
		    + '<select name="month" id="birthday_month"><option value="0">-月-</option></select> '
			+ '<select name="day" id="birthday_day"><option value="0">-日-</option></select>';
		return ret;		
	},
	write: function(){
		document.write(this.getHTML());
		
		this.bindHandlers();
	},
	fillData: function(year, month, day){
		var ny = new Date().getFullYear();
		for(var i = BirthdayChooser.YEAR_START; i<=ny; i++){
			var o;
			if(i==year) {
				o = new Option(i+"年", i);
			}
			else{
				o = new Option(i+"年", i);
			}
			$('birthday_year').options.add(o);
		}
		if(year!=0) $('birthday_year').selectedIndex = year-BirthdayChooser.YEAR_START+1;
		for(var i=1; i<=12; i++){
			var o = new Option(i+"月", i);
			$('birthday_month').options.add(o);
		}
		if(month!=0) $('birthday_month').selectedIndex = month;
		for(var i=1; i<=((month==2 && BirthdayChooser.isLeapYear(year))?29:BirthdayChooser.MONTH_DAY[month-1]); i++){
			var o = new Option(i+"日", i);
			$('birthday_day').options.add(o);
		}
		if(day!=0) $('birthday_day').selectedIndex = day;
		
		this.updateAstro();
	},
	fillDay: function(max){
		for(var i= $('birthday_day').options.length-1; i>=1; i--){
			$('birthday_day').remove(i);
		}
		for(var i=1; i<=max; i++){
			var o = new Option(i+"日", i);
			$('birthday_day').options.add(o);
		}
	},
	bindHandlers: function(){
		$('birthday_year').observe('change', function(){
			var y = ($('birthday_year').options[$('birthday_year').selectedIndex].value);
			var m = $('birthday_month').options[$('birthday_month').selectedIndex].value
			if(m==2){
				if(BirthdayChooser.isLeapYear(y))
					this.fillDay(29);
				else
					this.fillDay(28);
			}
			this.updateAstro();
		}.bindAsEventListener(this));

		$('birthday_month').observe('change', function(){
			var y = ($('birthday_year').options[$('birthday_year').selectedIndex].value);
			var m = $('birthday_month').options[$('birthday_month').selectedIndex].value
			if(m==2){
				if(BirthdayChooser.isLeapYear(y))
					this.fillDay(29);
				else
					this.fillDay(28);
			}else{
					this.fillDay(BirthdayChooser.MONTH_DAY[m-1]);
			}	
			this.updateAstro();
		}.bindAsEventListener(this));
		
		$('birthday_day').observe('change', function(){
			this.updateAstro();
		}.bindAsEventListener(this));
	},
	updateAstro: function(){
		var m = $('birthday_month').options[$('birthday_month').selectedIndex].value
		var d = $('birthday_day').options[$('birthday_day').selectedIndex].value
		$('astro').value = BirthdayChooser.getAstro(m,d);
//		alert(BirthdayChooser.getAstro(m,d));
	},
	setYear: function(year){
	},
	setMonth: function(month){
	},
	setDay: function(day){
	}
});

var StandardProp = Class.create();
Object.extend(StandardProp, {
	submit: function(event){
		event = $E(event);
		event.stop();
		var src = Event.element(event);
		var fv = src.serialize(true);
		if(src.gender_flag && !fv.gender_flag){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择性别', '错误', {});
			return false;
		}
		/*
		if(fv.bloodtype == ''){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择你的血型', '错误', {});
			return false;
		}
		*/
/*
		if(fv.marriage == ''){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择你的婚姻状况', '错误', {});
			return false;
		}
*/
/*
		if(fv.year =='-年-' || fv.month=='-月-' || fv.day=='-日-'){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择你的生日', '错误', {});
			return false;
		}
*/		
/*
		if(!fv.r_province){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择您的居住地', '错误', {});
			return false;
		}

		if(!fv.h_province){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择您的老家', '错误', {});
			return false;
		}
*/

		src.request({
			onComplete: function(transport){
				enable_form();
				var ret = (transport.responseText).evalJSON();
				if(ret.result){
					location.href='/';
				}else{
//					new MessageBox(MessageBox.TYPE_MESSAGE, __lang[ret.reason], '失败', {close: function(){ window.location.reload();}});
					MessageBox.showError(ret);
				}
			}
			
		});
		disable_form();
	},
	request: function(form){
		var src = $(form);
		var fv = src.serialize(true);
		if(src.gender && !fv.gender){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择性别', '错误', {});
			return false;
		}
		
		if(!fv.r_province || !fv.r_city || !fv.r_district){
			new MessageBox(MessageBox.TYPE_MESSAGE, '请选择您的居住地', '错误', {});
			return false;
		}

		src.request({
			onComplete: function(transport){
				enable_form();
				var ret = (transport.responseText).evalJSON();
				if(ret.result){
					location.href='/';
				}else{
					new MessageBox(MessageBox.TYPE_MESSAGE, __lang[ret.reason], '失败', {close: function(){ window.location.reload();}});
				}
			}
			
		});
		disable_form();
	}
});

var Notify = Class.create();
Object.extend(Notify, {
	submit: function(event){
		event = $E(event);
		event.stop();
		var src = Event.element(event);

		src.request({
			onComplete: function(transport){
				enable_form();
				var ret = (transport.responseText).evalJSON();
				if(ret.result){
					location.href='/';
				}else{
					new MessageBox(MessageBox.TYPE_MESSAGE, __lang[ret.reason], '失败', {close: function(){ window.location.reload();}});
				}
			}
			
		});
		disable_form();
	},
	request: function(form){
		var src = $(form);

		src.request({
			onComplete: function(transport){
				enable_form();
				var ret = (transport.responseText).evalJSON();
				if(ret.result){
					location.href='/';
				}else{
					new MessageBox(MessageBox.TYPE_MESSAGE, __lang[ret.reason], '失败', {close: function(){ window.location.reload();}});
				}
			}
			
		});
		disable_form();
	}
});

var BadUser = Class.create();
Object.extend(BadUser, {
	add:function(form){
		try{
			form = $(form);
			new Ajax.Request(
				form.action,
				{
					parameters: form.serialize (),
					onComplete: function(transport){
						enable_form();
						var ret = transport.responseText.evalJSON();
						if(ret.result){
							location.reload();
						}else{
							MessageBox.showError(ret);
						}				
				}
			});
		}catch(e){
		}
		disable_form();
		return false;
	},
	remove: function(form){
		form = $(form);
		form.request({
			onComplete: function(transport){
				enable_form();
				var ret = transport.responseText.evalJSON();
				if(ret.result){
					location.reload();
				}else{
					MessageBox.showError(ret);
				}
				
			}
		});
		disable_form();
		return false;
	}
});

function previewSig(text){
//http://bbs.ngacn.cc/nuke.php?func=bbcodetest&encode=utf-8&sign=ftgyhnjbhgcgfdrtgyhbgvfcgyh
	window.open('http://bbs.ngacn.cc/nuke.php?func=bbcodetest&encode=utf-8&sign='+text);
}

function insertArmorySig(region, realm, character){
	var text = '';
	var tag = region+"armory";
	text = "[" + tag + " " + realm + " " + character + "]";
	
	InsertText('nga_signature', text, true);
}

function disable_form(){
	$$('.sbtn').each(function(item){
		item.disabled = true;
	});
}

function enable_form(){
	$$('.sbtn').each(function(item){
		item.disabled = false;
	});
}

function formatTime(timestamp){
		var date = new Date(timestamp);
		var now = new Date().getTime() ;
		var diff = (now - timestamp)/1000;
		if(diff==0){
			ret = "1秒前";
		}else if(diff<60){
			ret = diff+"秒钟前";
		}else if(diff<3600){
			ret = Math.floor(diff/60)+"分钟前";
		}else if(diff<86400){
			ret = Math.floor(diff/3600)+"小时前";
		}else{
			ret = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
		}
		return ret;
}

var Deletion = Class.create();

Object.extend(Deletion.prototype, {
	target: null,
	duration: 300,
	step: 5,
	count: 0,
	height: 0,
	initialize: function(obj, duration){
		this.target = $(obj);
		this.height = this.target.getHeight();
		if(duration){
			this.duration = duration;
		}
		this.start();
	},
	start: function(){
		new PeriodicalExecuter(this.timer.bind(this), this.duration/this.step/1000); 
	},
	timer: function(pe){
		if(this.count == this.step){
			pe.stop();
			this.target.remove();
		}
		var ratio = 1- Math.sin(this.count/this.step * 3.1415926 / 2 );
//		var height = Math.ceil( ratio * this.height);
		this.target.setStyle({opacity: ratio});
		this.count++;
	}
});

function url_add(url, params){
	var p = url.toQueryParams();
	var s = url.indexOf('?')>=0?url.substr(0, url.indexOf('?')):url;
	var a = url.indexOf('#')>=0?url.substr(url.indexOf('#'), url.length):'';
	return s+"?"+$H(Object.extend(p, params)).toQueryString()+a;
}

var MessageChecker = Class.create();

Object.extend(MessageChecker, {
	hasNewMessage: false,
	pe: null,
	url: "/~sms.index.getNewSmsNum?"+Math.floor(Math.random()*100+1),
	title: null,
	i: 0,
	initialize: function(){
		this.pe = new PeriodicalExecuter (this.excute.bind(this), 120);
		this.excute(this.pe);
	},
	excute: function(pe){
		var self = this;
		var hp = false;
		if(document.getElementById("_new_pm_fri")) hp=true;
		new Ajax.Request(this.url, {
			onComplete: function(transport){
				try{
					var ret = transport.responseText.evalJSON();
					if(ret['result'] && parseInt(ret['data']['total'])>0){
						pe.stop();
						if(!self.title)  self.title = document.title;
						if(ret['data']['message']>0){
//							 url = "/~sms.index.view_inbox";
							 $('cnt_new_sms').innerHTML = '('+ret['data']['message']+")";
							 if(hp){
							 	$("_new_pm_sms").innerHTML = "<a href=\"/~sms.index.view_inbox/type/6\">"+ret['data']['message']+"条新</a>";
							}
						}
						if(ret['data']['system']>0){
//							 url = "/~sms.system.view_inbox";
							 $('cnt_new_sys').innerHTML = '('+ret['data']['system']+")";
							 if(hp){
							 	$("_new_pm_sys").innerHTML = "<a href=\"/~sms.system.view_inbox\">"+ret['data']['system']+"条新</a>";
							 }
						}
						if(ret['data']['announcement']>0){
//							 url = "/~sms.announcement.view_inbox";
							 $('cnt_new_ann').innerHTML = '('+ret['data']['announcement']+")";
							 if(hp){
								 $("_new_pm_ann").innerHTML = "<a href=\"/~sms.announcement.view_inbox\">"+ret['data']['announcement']+"条新</a>";
							 }
						}
						if(ret['data']['friends']>0){
//							 url = "/~sms.announcement.view_inbox";
							 if(hp){
								 $("_new_pm_fri").innerHTML = "<a href=\"/~sms.system.view_inbox/type/5\">"+ret['data']['friends']+"条新</a>";
							 }
						}
						if(ret['data']['comnum']>0){
							show = true;
//							url = "/~sms.comment.comment_list";
							$('cnt_new_com').innerHTML = '('+ret['data']['comnum']+")";
							if(hp){
								$("_new_pm_com").innerHTML = "<a href=\"/~sms.comment.comment_list\">"+ret['data']['comnum']+"条新</a>";
							}							
						}
						if(ret['data']['recomment']>0){
							show = true;
//							url = "/~sms.comment.mycomment_list";
							$('cnt_new_recom').innerHTML = '('+ret['data']['recomment']+")";
							if(hp){
								$("_new_pm_recom").innerHTML = "<a href=\"/~sms.comment.mycomment_list\">"+ret['data']['recomment']+"条新</a>";
							}
						}
						if(ret['data']['msgnum']>0){
							show = true;
							$('cnt_new_msg').innerHTML = '('+ret['data']['msgnum']+")";
//							url = "/~sms.comment.message_list";
							if(hp){
								$("_new_pm_msg").innerHTML = "<a href=\"/~sms.comment.message_list\">"+ret['data']['msgnum']+"条新</a>";								
							}
						}
						if(ret['data']['remsgnum']>0){
							show = true;
//							url = "/~sms.comment.mymessage_list";
							$('cnt_new_remsg').innerHTML = '('+ret['data']['remsgnum']+")";
							if(hp){
								$("_new_pm_remsg").innerHTML = "<a href=\"/~sms.comment.mymessage_list\">"+ret['data']['remsgnum']+"条新</a>";
							}
						}
//						$('sms_link').setAttribute('href',url);
						$('new_pm_icon').show();
						/*
						$H(ret['data']).each(function(item){
							var span = null;
							if(span = $('n_'+item.key)){
								span.innerHTML = item.value>0?item.value:0;
								if(!(item.value>0)){
									$('msg_'+item.key).hide();
								}else{
									$('msg_'+item.key).show();
								}
							}
						});
						$('messageBox').show();
						*/
						new PeriodicalExecuter(self.blinkTitle.bind(self), 1);
					}else{
						//$('messageBox').hide();
					}

					if(!ret['result']){
						pe.stop();
					}
				}catch(e){
					//alert(e.message);
				}
			}
		});
	},
	blinkTitle: function(pe){
		var star = (this.i%2==0)?'★':'☆';
		document.title = star+'新消息'+star + " " + this.title;
		pe.stop();
		new PeriodicalExecuter(this.blinkTitle.bind(this), this.i%2==0?2:1);
		this.i++;
	}
});

function disable_submit_btn(){
	$$('.submit_btn').each(function(item){
		item.disabled = true;
	});
}

function enable_submit_btn(){
	$$('.submit_btn').each(function(item){
		item.disabled = false;
	});
}

var SystemMessage = Class.create();
Object.extend(SystemMessage, {
	call: function(msg_id, obj, func, args){
		var onComplete = function(transport){
			var ret = transport.responseText.evalJSON();
			if(ret['result']){
				$('msg_'+msg_id).innerHTML = ret['data'];
				callFunction();
			}
		};

		var callFunction = function(){
			try{
				obj[func].apply(obj, args);
			}catch(e){
				alert(e.message);
			}
		}
		new Ajax.Request( '/~sms.system.update_status',{
			parameters: $H({id: msg_id, type: func}),
			onComplete: onComplete,
			asynchronous: false
		});
	}

});

var SmilePanel = Class.create();

Object.extend(SmilePanel.prototype, {
	id: '',
	chooseFunc: null,
	trigger: null,
	initialize: function(id, trigger, chooseFunc){
		this.id = id;
		this.chooseFunc = chooseFunc;
		this.trigger = $(trigger);

	},
	bindHandlers: function(){
		$('smile_'+this.id).observe('click', this.chooseSmile.bindAsEventListener(this));
		Event.observe(document.body, 'click', this.cancelPanel.bindAsEventListener(this));
	},	
	show: function(event, adjust){
		event = $E(event);
		var src = Event.element(event);
		
		if($('smile_'+this.id) && $('smile_'+this.id).getStyle('display')!='none'){
			$('smile_'+this.id).hide();
			return;
		}

		if(!$('smile_'+this.id)){
			var text = this.genHTML();
			$(document.body).insert({bottom: text});
			this.bindHandlers();
		}

		var offset = src.cumulativeOffset();
		var dem = src.getDimensions();
		var left = offset.left;
		var top = offset.top + dem.height ;
		if(adjust){
			left += adjust.left;
			top += adjust.top;
		}

		$('smile_' + this.id).absolutize ();
		$('smile_' + this.id).setStyle({
			left: left + 'px',
			top: top + 'px'
		});

		$('smile_' + this.id).show();
	},
	genHTML: function(){
		var text = '<div id="smile_'+this.id+'" style="outline:none;z-index:99">\
		<div class="smile-wrap">\
		<div  class="simgs"  >';

		for(var i=1; i<=64; i++){
			text += '<img style="width: 21px; height: 21px;" src="/res/comment/images/smiles2/em'+i+'.gif" index="'+i+'" class="smile"/>';
		}

		text += "</div></div></div>";

		return text;
	},
	cancelPanel: function(event){
		event = $E(event);
		var src = Event.element(event);
		if(src.descendantOf('smile_'+this.id) || src==$('smile_'+this.id) || src.id==this.trigger.id){
		}else{
			$('smile_'+this.id).hide();
		}
	},
	chooseSmile: function(event){
		event = $E(event);
		var src = Event.element(event);
		if(src.hasClassName('smile')){
			var index = src.getAttribute('index');
			this.chooseFunc.call(null, index);
			$('smile_'+this.id).hide();
		}
	}
});

var SystemMessageRedirect = Class.create();
Object.extend(SystemMessageRedirect, {
	redirect: function(url){
//		alert(url);
		location.href = url;
	}
});

var Tooltip = Class.create();
Object.extend(Tooltip, {
	t: '<div id="buff_tooltip" class="icontext" style="z-index:99; display: none"></div>',
	show: function(event, text, adjust, dock){
		try{
		if(!dock){dock='ver';}
		if(!adjust){
			adjust = {left:0, top:0};
		}
		event = $E(event);
		var src = Event.element(event);

		var offset = src.cumulativeOffset();
		var dem = src.getDimensions();
		
		if(! $('buff_tooltip')){
			$(document.body).insert({bottom: Tooltip.t});
		}
		$('buff_tooltip').innerHTML = text;
		$('buff_tooltip').absolutize();
		$('buff_tooltip').setStyle({ 
			top: ((dock=='ver')?(offset.top + dem.height + adjust.top): (offset.top + adjust.top)) + 'px', 
			left: ((dock=='ver')?(offset.left + adjust.left):(offset.left + dem.width + adjust.left))+'px'});
		$('buff_tooltip').show();
		}catch(e){
			alert(e);
		}

	},
	close: function(event){
		if($('buff_tooltip'))$('buff_tooltip').remove();
	}
});

function search_focus(input){
	$(input).removeClassName('disable_form');
	if(input.value.trim()=='搜索用户' || input.value.trim()=='输入对方昵称进行搜索'){
		input.value = '';
	}
	$(input).setStyle({color:'000'});
}

function search_blur(input){
	if($(input).value.trim()=='' ){
		input.value = '输入对方昵称进行搜索';
		$(input).addClassName('disable_form');
	}
	
	$(input).setStyle({color:'gray'});
}

function search_submit(input){
	if($(input).value == '' || $(input).hasClassName('disable_form')){
		$(input).value = '输入对方昵称进行搜索';
		return false;
	} else {
		new Ajax.Request('/?_app=index&_controller=search&_action=user', {
			parameters: 'key=' + $(input).value + '&r=' + Math.random(),
			onComplete: function(transport) {
				var ret = transport.responseText.evalJSON();
				if (ret.result && ret.data) {
					location.href = '/?uid=' + ret.data;
				} else {
					new MessageBox(MessageBox.TYPE_MESSAGE, '您搜索的用户不存在', '提示', {close:function(){}});
				}
			}
		})
	}
	return false;
}

function copyInputString(input){
	$(input).select();
	txt = $(input).value;
	if(window.clipboardData) {
		window.clipboardData.clearData();
		window.clipboardData.setData("Text", txt);
	} else if(navigator.userAgent.indexOf("Opera") != -1) {
		window.location = txt;
	} else if (window.netscape) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		} catch (e) {
			if(!this['checked']){
				this['checked'] =true;
				alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试");
			}
			return false;
		}
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip)return;
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans)	return;
		trans.addDataFlavor('text/unicode');
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext = txt;
		str.data = copytext;
		trans.setTransferData("text/unicode",str,copytext.length*2);
		var clipid = Components.interfaces.nsIClipboard;
		if (!clip)	return false;
		clip.setData(trans,null,clipid.kGlobalClipboard);

	}
	return true;

}

var FlyMessage = Class.create();
Object.extend(FlyMessage, {
//	messageTemplate: '<div id="float_message_#{index}" style="position:absolute; z-index: #{zindex}; display: ; left: 200px; top: 100px" index="#{index}">#{content}</div>',
	messageTemplate: '<div class="right-popup" style="position: absolute; z-index:300;  display: ;left: 200px; top: 50px; width: 200px" id="fly_message_#{index}"  index="#{index}><div class="popup">\
	<div class="popup-top">\
		<div class="popup-top-right">\
			<div class="popup-top-mid"></div>\
		</div>	\
	</div>\
	<div class="popup-mid">\
		<div class="popup-mid-main">\
		  <div class="popup-mid-main-mid">\
			  <div class="popup-mid-main-mid-content">\
                    <p class=" friendly-tip-pop"><span class="fixie6png tip-icon friendly-tip-icon"></span>\
<span class="content_popup">#{content}</span>    \
                    </p>\
\
		    </div>\
		  </div>\
			  \
			  \
	  </div>	  \
	</div>\
	\
	<div class="popup-bottom">\
		<div class="popup-bottom-right">\
			<div class="popup-bottom-mid"></div>\
		</div>\
	</div>\
\
</div>\
</div>',
	queue: [],
	index: 0,
	inCount: 0,
	outCount: 0,
	status: 'waiting',
	running: 0,
	add: function(text, duration){
		if(text.trim()=='') return;
		var message = new FlyMessage(text, duration);
		this.queue.push(message);
	},
	playQueue: function(){
		new PeriodicalExecuter(this.playMessage.bind(this), 0.1);
		$('FlyMessages').observe('click', this.onCleanClick);
	},
	playMessage: function(pe){
		if(this.queue.length>0 ){
			for(this.index; this.index<this.queue.length; this.index++){
				this.queue[this.index].play(this.index);
			}
		}
	},
	clean: function(){
		this.index = 0;
		this.queue = [];
		this.inCount = 0;
		this.outCount = 0 ;
		this.status = "waiting";
	},
	prepareIn: function(){
		this.pos 			= this.content.cumulativeOffset();
		this.dimension 		= this.content.getDimensions();
		var scrollTop		= document.documentElement.scrollTop;
		var scrollLeft		= document.documentElement.scrollLeft;
		var clientWidth		= document.documentElement.clientWidth;
		var clientHeight	= document.documentElement.clientHeight;
		
		var sp = [];
		sp[0] = this.pos.left;
		sp[1] = this.pos.top ;
		for(var i=0; i<=FlyMessage.index; i++){
			if(FlyMessage.queue[i].status=='remove'){
				continue;
			}
			sp[1] +=  FlyMessage.queue[i].obj.getDimensions().height +8;
		}
		
		if(this.direction==1){
			this._startPos = sp;
			this._endPos = this.pos;
		}else{
			this._startPos = this.pos;
			this._endPos = sp;
		}
		this.content.setStyle({left: this._startPos[0] + "px", top: this._startPos[1] +"px"});
	},
	prepareOut: function(){
		this.pos 			= this.content.cumulativeOffset();
		this.dimension 		= this.content.getDimensions();
		var scrollTop		= document.documentElement.scrollTop;
		var scrollLeft		= document.documentElement.scrollLeft;
		var clientWidth		= document.documentElement.clientWidth;
		var clientHeight	= document.documentElement.clientHeight;
		
		var sp = [];
		sp[0] = this.pos.left;
		sp[1] = -10 - this.dimension.height;
		
		if(this.direction==1){
			this._startPos = sp;
			this._endPos = this.pos;
		}else{
			this._startPos = this.pos;
			this._endPos = sp;
		}
		this.content.setStyle({left: this._startPos[0] + "px", top: this._startPos[1] +"px"});
	},
	onCleanClick: function(event){
		var flag = 0;
		event = $E(event);
		var src = Event.element(event);
//		if(!src.hasClassName('clewrightclose')) return;
		for(var i=0; i<FlyMessage.queue.length; i++){
			if(FlyMessage.queue[i].status=='stop' || FlyMessage.queue[i].status=='remove'){
				flag ++;
			}
		}
		if(flag == FlyMessage.queue.length){
			for(var i=0; i<FlyMessage.queue.length; i++){
				FlyMessage.queue[i].obj.observe('transition:complete', FlyMessage.queue[i].transitionOut.bindAsEventListener(FlyMessage.queue[i].obj));
				FlyMessage.queue[i].status = "remove";
				TransitionManager.start({content: FlyMessage.queue[i].obj, direction: 0, 
					duration:1.2, easing: Elastic.easeOut, startPoint:2, type: Fly, index: i, _prepare: FlyMessage.prepareOut});
			}
		}
	}
});

Object.extend(FlyMessage.prototype, {
	text: '',
	duration: 2,
	obj: null,
	status: '',
	initialize: function(text, duration){
		this.text = text;
		this.duration = duration;
	},
	play: function(index){
		var message = new Template(FlyMessage.messageTemplate).evaluate({content: this.text, index: index, zindex: index+1000});
		$('FlyMessages').insert({bottom:message});
		this.obj = $('fly_message_'+index);
		this.obj.observe('transition:complete', this.transitionIn.bindAsEventListener(this));
		this.setPosition();
		TransitionManager.start({content: this.obj, direction: 0, 
			duration:this.duration, easing: Elastic.easeOut, startPoint:8, type: Fly, index: index, _prepare: FlyMessage.prepareIn});
	},
	setPosition: function(){
		var scrollTop		= document.documentElement.scrollTop;
		var scrollLeft		= document.documentElement.scrollLeft;
		var clientWidth		= document.documentElement.clientWidth;
		var clientHeight	= document.documentElement.clientHeight;
		var dimension = this.obj.getDimensions();
		var offset = this.obj.cumulativeOffset ();

		this.obj.setStyle({left: (clientWidth-dimension.width + scrollLeft - 20) + "px", top: ((scrollTop>105)?(scrollTop-50):(offset.top)) + "px"});
	},
	transitionIn: function(event){
		event = $E(event);
		var src = Event.element(event);
		src.stopObserving('transition:complete', this.transitionIn.bindAsEventListener(this));
		if(this.status!='remove'){
			this.status = 'stop';
		}
	},
	transitionOut: function(event){
		event = $E(event);
		var src = Event.element(event);
//		src.remove();
	}
});

var TransitionManager = Class.create();
Object.extend(TransitionManager, {
	queue: [],
	start: function(params){
		var t = new params.type(params);
		t.start();
	}
});
var Transition = Class.create();
Object.extend(Transition.prototype, {
	direction: 1,
	duration: 2,
	easing: {},
	content: null,
	startPoint: 1,
	startTime: 0,
	_startPos:[],
	_endPos:[],
	initialize: function(params){
		Object.extend(this, params);
		this._prepare();
	},
	start: function(){
		this.startTime = new Date().getTime();
		new PeriodicalExecuter(this.perframe.bind(this), 1/30);
	},
	getContentDimensions: function(){
		return this.content.getDimensions();
	},
	perframe: function(pe){
		var now = new Date().getTime();
		var t = (now - this.startTime)/1000;
		if(t>this.duration){
			this.content.fire("transition:complete");
			pe.stop();
		}else{
			var p = this.easing(t, 0, 1, this.duration, 1, 8);
			this.render(p);
		}
	},
	render: function(p){
		
	}
});
var Fly = Class.create();
Object.extend(Fly.prototype, Transition.prototype);
Object.extend(Fly.prototype, {
	pos: {},
	dimension: {},
	_prepare: function(){
		this.pos = this.content.cumulativeOffset();
		this.dimension = this.content.getDimensions();
		var scrollTop		= document.documentElement.scrollTop;
		var scrollLeft		= document.documentElement.scrollLeft;
		var clientWidth		= document.documentElement.clientWidth;
		var clientHeight	= document.documentElement.clientHeight;

		var sp = [];
//		alert(this.startPoint);
		switch(this.startPoint){
			default:
			case 1: // 左上
				sp[0] = scrollLeft;
				sp[1] = scrollTop;
			break;
			case 2: // 中上
				sp[0] = this.pos.left;
				sp[1] =  scrollTop;
			break;
			case 3: // 右上
				sp[0] = scrollLeft + clientWidth - this.dimension.width;
				sp[1] = scrollTop;
			break;
			case 4: //左中
				sp[0] = scrollLeft;
				sp[1] = this.pos.top;
			break;
			case 5: // 中
				sp[0] = scrollLeft + (clientWidth - this.dimension.width)/2;
				sp[1] = scrollTop + (clientHeight - this.dimension.height)/2;
				break;
			break;
			case 6: // 右中
				sp[0] = scrollLeft + clientWidth - this.dimension.width;
				sp[1] = this.pos.top;
			break;
			case 7: // 左下
				sp[0] = this.pos.left;
				sp[1] = scrollTop + clientHeight - this.dimension.height;
			break;
			case 8: // 中下
				sp[0] = this.pos.left;
				sp[1] = scrollTop + clientHeight - this.dimension.height;
			break;
			case 9: // 右下
				sp[0] = scrollLeft + clientWidth - this.dimension.width;
				sp[1] = scrollTop + clientHeight - this.dimension.height;
			break;
		}
		sp[0] = Math.round(sp[0]);
		sp[1] = Math.round(sp[1]);
		if(this.direction==1){
			this._startPos = sp;
			this._endPos = this.pos;
		}else{
			this._startPos = this.pos;
			this._endPos = sp;
		}
		this.content.setStyle({left: sp[0] + "px", top: sp[1] +"px"});
	},
	render: function(p){
		var _x = Math.round(this._endPos[0] + (this._startPos[0]-this._endPos[0]) * (1-p));
		var _y = Math.round(this._endPos[1] + (this._startPos[1]-this._endPos[1]) * (1-p));
		
		this.content.setStyle({left: _x + "px", top: _y +"px"});
		this.content.show();
	}
});
var Elastic = Class.create();
Object.extend(Elastic, {
	easeOut: function(t, b, c, d, a, p){
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
	},
	easeIn: function(t, b, c, d, a, p){
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	}
});

var Bounce = Class.create();
Object.extend(Bounce,{
	easeOut: function (t, b, c, d){
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeIn: function (t, b, c, d){
		return c - Bounce.easeOut (d-t, 0, c, d) + b;
	}
});

var Combo = Class.create();
Object.extend(
	Combo.prototype,{
		id: '',
		options: [],
		filter:[],
		dropBounds: {},
		dropPositions: {},
		dropBounds2: {},
		dropPositions2: {},
		absolute: false,
		initialize: function(id, options, abs){
			this.id = id;
			this.bindEventListener();
			this.setOptions(options);
			this.absolute = abs?true:false;
		},
		cleanOptions: function(){
			this.options = [];
		},
		setOptions: function(opts){
			this.options = opts;
			this.filter = this.filterOption();
			$(this.id).fire("combo:datachange", {data: this.filter});
		},
		addOption: function(opt){
			this.options.push(opt);
		},
		filterOption: function(){
			var input = $(this.id).value.trim();
			if(input == ''){
				return [];
			}else{
				return this.options.findAll(function(o){
					var match = ((o.length<3)?o[1]:(o[2] + "," + o[1])).split(",");
					var contains = false;
					match.each(function(str){
						if(str.indexOf(input)>=0){
							contains = true;
							throw $break;
						}
					});
					return contains;
				});
			}
		},
		bindEventListener: function(){
			$(this.id).observe('focus', this.onCursorIn.bindAsEventListener(this));
//			$(this.id).observe('blur', this.onCursorOut.bindAsEventListener(this));
			$(this.id).observe('combo:change', this.onKeyPress.bindAsEventListener(this));
			$(this.id).observe('keyup', this.onKeyPress.bindAsEventListener(this));
			$(this.id).observe('keydown', this.onOptionChoose.bindAsEventListener(this));
			if($(this.id + "_dropbtn")!=null){
				$(this.id + "_dropbtn").observe('click', this.onDropBtnClick.bindAsEventListener(this));
			}
			$(this.id + "_drop").observe('click', this.onOptionChooseByClick.bindAsEventListener(this));
			
			$(this.id).observe('combo:datachange', this.onDataChange.bindAsEventListener(this));
			Event.observe(document.body, "click", this.onClickOutside.bindAsEventListener(this));
		},
		scrollDrop: function(item, direction){
			var obj = $$("#"+this.id + "_drop ul")[0];
			var offset = item.cumulativeOffset();
			var item_height = item.getDimensions()['height'];
			var relative_y = offset.top - this.dropPositions.top - obj.scrollTop + ((direction=="down")?item_height:0);
			if(relative_y>0){
				if(relative_y > this.dropBounds.height){
					var previous = item.previous();
					var pre_offset = previous.cumulativeOffset();
					obj.scrollTop = pre_offset.top - this.dropPositions.top;
				}
			}else{
				obj.scrollTop = offset.top - this.dropPositions.top;
			}
		},
		onClickOutside: function(event){
			event = $E(event);
			var src = Event.element(event);
			if(src==$(this.id+"_frame") || src.descendantOf(this.id+"_frame")){
				
			}else{
				this.hideDropDown();
			}
		},
		onOptionChoose: function(event){
			event = $E(event);
			var code = event.keyCode;

			switch(code){
				case 9:  // tab
//					this.hideDropDown();
					break;
				case 38: // up 
					var item = this.findPrevious();
					if(item!=null){
						var items = $$("#" + this.id + "_drop ul li");
						items.each(function(i){
							i.removeClassName('combo-current');
						});
						item.addClassName('combo-current');
						this.scrollDrop(item, items[items.length-1] == item?"down":"up");
					}
				break;
				case 40: // down
					var item = this.findNext();
					if(item!=null){
						var items = $$("#" + this.id + "_drop ul li");
						items.each(function(i){
							i.removeClassName('combo-current');
						});
						item.addClassName('combo-current');
						this.scrollDrop(item, items[0] == item?"up":"down");
					}
				break;
				case 13: // enter
					var index = 0;
					var item = $$("#" + this.id + "_drop ul li").find(function(item, i){
						index = i;
						return item.hasClassName("combo-current");
					});
					this.setValue(index);
					Event.stop(event);
				break;
				default:
				break;
			}
		},
		onKeyPress: function(event){
			event = $E(event);
			var code = event.keyCode;
			switch(code){
				case 9:  // tab
//					this.hideDropDown();
					break;
				case 37: // left 
				case 38: // up 
				case 39: // right
				case 40: // down
				break;
				case 13: // enter
					Event.stop(event);
				default:
					this.filter = this.filterOption();
					$(this.id+"_selected").value = $(this.id).value;
					$(this.id).fire("combo:datachange", {data: this.filter});
					this.showDropDown();
				break;
			}
		},
		onCursorIn: function(event){
			this.showDropDown();
		},
		onCursorOut: function(event){
			this.hideDropDown();
		},
		onDropBtnClick: function(event){
			this.toggleDropDown();
		},
		onOptionChooseByClick: function(event){
			event = $E(event);
			var src = Event.element(event);
			if(src.tagName!='LI'){
				src = src.parentNode;
			}
			var index = $$("#" + this.id + "_drop ul li").indexOf(src);
			this.setValue(index);
			$(this.id).fire('combo:change');
		},
		onDataChange: function(event){
			event = $E(event);
			this.renderDropDown(event.memo.data);
		},
		toggleDropDown: function(){
			$(this.id+"_"+"drop").toggle();
		},
		showDropDown: function(){
			var show = false;
			if(this.filter.length>0){
				if(this.filter.length==1){
					if(this.filter[0][1] != $(this.id).value){
						show = true;
					}else{
						this.setValue(0);
					}
				}else{
					show = true;
				}
			}
			if(show){
				$(this.id+"_"+"drop").show();
				$(this.id+"_"+"drop").absolutize();
				this.dropBounds = $(this.id+"_"+"drop").getDimensions();
				this.dropPositions = $(this.id+"_"+"drop").cumulativeOffset();
				this.dropBounds2 = $(this.id).getDimensions();
				this.dropPositions2 = $(this.id).cumulativeOffset();
//				$(document.body).insert("<div style='border: 1px solid red; position: absolute; left:"
//					+ this.dropPositions2.left + "px; top:" 
//					+ this.dropPositions2.top + "px; width:"
//					+ this.dropBounds2.width + "px; height:"
//					+ this.dropBounds2.height+"px'></div>");
				if(this.absolute){
					$(this.id+"_"+"drop").setStyle({
						top: (this.dropPositions2.top+this.dropBounds2.height)+"px"
					});
				}
				$$("#"+this.id + "_drop ul")[0].scrollTop = 0;
				
				var current = $$("#" + this.id + "_drop ul li")[0];
				$$("#" + this.id + "_drop ul li").each(function(item){
					item.removeClassName('combo-current');
				});
				current.addClassName("combo-current");
			}else{
				this.hideDropDown();
			}
		},
		hideDropDown: function(){
			$(this.id+"_"+"drop").hide();
		},
		renderDropDown: function(items){
			var container = $$("#" + this.id + "_drop ul")[0];
			container.innerHTML = "";
			items.each(function(item, i){
				if(i>=50) throw $break;
				container.insert("<li><a href='javascript:void(0);'>"+item[1]+"</a></li>");
			});
		},
		findNext: function(){
			var lis = $$("#" + this.id + "_drop ul li");
			if(lis.length==0){
				return null;
			}
			if(lis.length==1){
				return lis[0];
			}
			var ret = lis.find(function(item){
				return item.hasClassName("combo-current");
			});
			if(ret == null){
				return lis[0];
			}
			
			ret = ret.next();
			if(ret==null){
				return lis[0];
			}else{
				return ret;
			}
		},
		findPrevious: function(){
			var lis = $$("#" + this.id + "_drop ul li");
			if(lis.length==0){
				return null;
			}
			if(lis.length==1){
				return lis[0];
			}
			var ret = lis.find(function(item){
				return item.hasClassName("combo-current");
			});
			if(ret == null){
				return lis[0];
			}
			
			ret = ret.previous();
			if(ret==null){
				return lis[lis.length-1];
			}else{
				return ret;
			}
		},
		setValue: function(index){
			try{
//			if(this.filter[index]){
				$(this.id).value = this.filter[index][1];
				$(this.id+"_selected").value = this.filter[index][0];
//			}
			this.hideDropDown();
			$(this.id).select();
			$(this.id).focus();
			}catch(e){}
		}
	}
);

var Debug = Class.create();
Object.extend(Debug, {
	instance: null,
	log: function(id, str){
		if(!this.instance){
			this.instance = new Debug(id);
		}
		this.instance.log(str);
	}
});
Object.extend(Debug.prototype, {
	id: '',
	initialize: function(id){
		this.id = id;
		if($(this.id)){
			$(this.id).setStyle({overflow: "auto", height: "200px", width:"400px", border:"1px solid red", margin:"10px"});
		}
	},
	log: function(str){
		if($(this.id)){
			$(this.id).insert("<div style='border-bottom: 1px solid gray'>"+str+"</div>");
			$(this.id).scrollTop = $(this.id).scrollHeight;
		}
	}
});

var FriendList = Class.create();
Object.extend(
	FriendList.prototype, 
	{
		id:'',
		multi: false,
		max: 0,
		currentGroupName: null,
		lists: {},
		groupLoaded: false,
		group: [],
		initialize: function(id, multi, max){
			this.id = id;
			this.multi = multi;
			this.max = max;
			this.bindEventListeners();
		},
		bindEventListeners: function(){
			$(this.id+"_dropbtn").observe('click', this.onDropBtnClick.bindAsEventListener(this));
			$(this.id+"_ok").observe('click', this.onFriendChooseOK.bindAsEventListener(this));
			$(this.id+"_reset").observe('click', this.onFriendChooseReset.bindAsEventListener(this));
			$(this.id+"_group").observe('change', this.onGroupSelect.bindAsEventListener(this));
			$(this.id).observe("flist:query_friends", this.onQueryFriends.bindAsEventListener(this));
			$(this.id).observe("flist:query_friends_group", this.onQueryFriendsGroup.bindAsEventListener(this));
		},
		onDropBtnClick: function(event){
			$(this.id + "_drop").toggle();
			var dem = $(this.id + "_dropbtn").getDimensions();
//			var pos = $(this.id + "_dropbtn").cumulativeOffset ();
			var pos = {
				left: $(this.id + "_dropbtn").offsetLeft, 
				top: $(this.id + "_dropbtn").offsetTop
			};
			
			var drop_dem = $(this.id + "_drop").getDimensions();
			var drop_pos = $(this.id + "_drop").cumulativeOffset();
			var left = pos.left + dem.width - drop_dem.width;
			var top = pos.top + dem.height;
			$(this.id + "_drop").setStyle({ left: left+"px", top: top+"px"});
			$(this.id).fire("flist:query_friends");
			$(this.id).fire("flist:query_friends_group");
		},
		onQueryFriends: function(event){
			var url = "/~friends.group.get_group_user";
			var group = $(this.id + "_group");
			var group_name = group.options[group.selectedIndex].value;
			if(!this.lists[group_name]){
				$(this.id + "_loading").show();
				$(this.id + "_content").hide();
				new Ajax.Request(url, {
					parameters: $H({'group_id':group_name}),
					onComplete: this.onFriendListLoaded.bindAsEventListener(this, group_name)
				});
			}else{
				if(this.currentGroupName != group_name){
					this.fillList(this.lists[group_name], group_name);
					this.currentGroupName = group_name;
				}
			}
		},
		fillList: function (list, gname){
			$(this.id+'_fill').innerHTML = '';
			this.lists[gname] = list;
			
			list.each(function(item){
				$(this.id+'_fill').insert('<li><input name="'+this.id+'_item" class="'+this.id+'-item" type="'
					+(this.multi?'checkbox':'radio')+'" value="'
					+item.username+'" id="'
					+(this.id+"_"+gname+"_"+item.uid)+'"><label for="'
					+(this.id+"_"+gname+"_"+item.uid)+'">'
					+(item.username.truncateCn(11))+'</label></li>');
			}.bind(this));
		},
		fillGroup: function(groups){
			var group = $(this.id + "_group");
			if(groups instanceof  Array){
				groups = $A(groups);
			}else{
				groups = $H(groups)
			}
			groups.each(function (item){
				if(item.value['group_nums']>0){
					group.options.add(new Option(item.value['group_name'], item.key));
				}
			});
		},
		onQueryFriendsGroup: function(event){
			if(!this.groupLoaded){
				var url = "/~friends.group.get_all_group";
				new Ajax.Request(url, {
					onComplete: this.onFriendGroupLoaded.bindAsEventListener(this)
				});
			}
		},
		onFriendListLoaded: function(t, gname){
			try{
				$(this.id + "_loading").hide();
				$(this.id + "_content").show();
				var ret = t.responseText.evalJSON();
				if(ret.result){
					this.fillList(ret['data'], gname);
				}
				this.currentGroupName = gname;
			}catch(e){alert(e);}
		},
		onGroupSelect: function(event){
			$(this.id).fire("flist:query_friends");
		},
		onFriendChooseOK: function(event){
			if(this.multi){
				var checks = $$("."+this.id+"-item").findAll(function(item){
					return item.checked;
				}).map(function(item){
					return item.value;
				});
				var friends = $A(($(this.id).value.trim()==""?[]:$(this.id).value.trim().split(",")).concat(checks)).uniq().slice(0, this.max>0?this.max:50);
				$(this.id).value = friends.join(",");
			}else{
				$(this.id).value = $$("." + this.id + "-item").find(function(item){
					return item.checked;
				}).value;
			}
			$(this.id+"_drop").hide();
		},
		onFriendChooseReset: function(event){
			$$(".flist-item").each(function(item){
				item.checked = false;
			});
			$(this.id+"_drop").hide();
		},
		onFriendGroupLoaded: function(t){
			try{
				var ret = t.responseText.evalJSON();
				if(ret.result){
					this.groupLoaded = true;
					this.fillGroup(ret['data']);
				}
			}catch(e){
//				alert(e.message);
			}
		}
	}
);

var Tips = Class.create();
Object.extend(Tips, {
	add:function (id, html, override_show_events, override_hide_events){
		if(override_show_events==null){
			override_show_events = ["mouseover"];
		}
		if(override_hide_events==null){
			override_hide_events = ["mouseout"];
		}
		
		override_show_events.each(function(event){
			$(id).observe(event, this.show.bindAsEventListener(this,id, html));
		}.bind(this));
		override_hide_events.each(function(event){
			$(id).observe(event, this.hide.bindAsEventListener(this,id, html));
		}.bind(this));		
	},
	show:function(event, id, html){
		if($("tooltip") == null){
			$(document.body).insert('<div class="floating-tip" id="tooltip" style="position: absolute; display: none"></div>');
		}
		$('tooltip').innerHTML = '';
		$('tooltip').insert(html);

		var len = 0;
		for (var i = 0; i < html.length; i++) {
			len += (html.charCodeAt(i) > 256) ? 2 : 1;
		}
		if (len > 100) {
			$('tooltip').setStyle({ width: "300px"});
		} 
		
		var dem = $(id).getDimensions();
		var pos = $(id).cumulativeOffset();
		$('tooltip').setStyle({
			left: pos.left+"px",
			top: (pos.top + dem.height)+"px"
		});
		$('tooltip').show();
	},
	hide: function(event, html){
		$('tooltip').hide();
	}
});

var ErrorTips = Class.create();
Object.extend(
	ErrorTips,
	{	
		tips: {},
		add: function(item, type, html, style)	{
			item = $(item);
			if(this.tips[item]){
				this.remove(item);
			}
			this.tips[item] = new Element('div');
			this.tips[item].setStyle({position: 'absolute'});
			if(style){
				this.tips[item].setStyle(style);
			}
			this.tips[item].insert(
				'<div class="tip-box friendly-tip-box"><div class="friendly-tip"><div> <span class="fixie6png tip-icon '+type+'-tip-icon"></span>'+html+'</div></div></div>'
			);
			$(document.body).insert(this.tips[item]);
			this.position(item);
		},
		remove: function(item){
			this.tips[item].remove();
			this.tips[item] = null;
		},
		position: function(item){
			var dem = item.getDimensions();
			var pos = item.cumulativeOffset();
			
			this.tips[item].setStyle({
				top: pos.top + "px"	,
				left: (pos.left + dem.width) + "px"
			});
		}
	}
);

var FloatMessage = Class.create();
Object.extend(
	FloatMessage,
	{
		template: '<div class="right-popup" style="position: absolute; z-index:400"><div class="popup">\
	<div class="popup-top">\
		<div class="popup-top-right">\
			<div class="popup-top-mid"></div>\
		</div>	\
	</div>\
	<div class="popup-mid">\
		<div class="popup-mid-main">\
		  <div class="popup-mid-main-mid">\
			  <div class="popup-mid-main-mid-content">\
                    <p class=" friendly-tip-pop"><span class="fixie6png tip-icon friendly-tip-icon"></span>\
<span class="content_popup">#{html}</span>    \
                    </p>\
\
		    </div>\
		  </div>\
			  \
			  \
	  </div>	  \
	</div>\
	\
	<div class="popup-bottom">\
		<div class="popup-bottom-right">\
			<div class="popup-bottom-mid"></div>\
		</div>\
	</div>\
\
</div>\
</div>',
		show: function(type, html, duration){
			var template = new Template(this.template);
			var div = $($D(template.evaluate({html: html})));
			$(document.body).insert(div);
			var clientHeight = document.documentElement.clientHeight ;
			var clientWidth = document.documentElement.clientWidth;
			var content_width = 0
			div.descendants().each(function(item){
				if(item.hasClassName('content_popup')){
					content_width = item.getWidth();
					throw $break;
				}
			});
			var width = content_width + 100;
			var height = div.getHeight();
			
			div.setStyle({
				left: Math.floor((clientWidth - width)/2) +"px",
				top: Math.floor((clientHeight - height)/2) +"px",
				width: width+"px"
			});
			
			new PeriodicalExecuter(
				function(pe){
					pe.stop(); 
					new Deletion(div)
				},2
			);
		}
	}
);

//FlyMessage.add("aaaaa", 4);
//FlyMessage.add("aaaaa", 4);
//FlyMessage.add("aaaaa", 4);
//for(var i=0; i<2; i++){
//FlyMessage.add(i, 0.5);
//}
//Event.observe(window, 'load', function(){ new PeriodicalExecuter(function(pe){FlyMessage.playQueue(); pe.stop();}, 1);});